//
function my_ajax(options) {
    $.ajax({
        type: options.type == null ? "POST" : options.type,
        dataType: "json",
        data: options.data,
        contentType: options.contentType == null ? "application/json;charset=utf-8" : options.contentType,
        url: "http://120.55.165.31:8080/Elearning/api" + options.url,
        success: options.success,
        error: options.error == null ? function () {
            alert("ajax失败");
        } : options.error,
        async: options.async == null ? false : options.async
    });
}

// 定制化ajax
function message_ajax(apiUrl, messageId) {
    let options = {
        data: JSON.stringify({token: get_token(), messageId: messageId}),
        url: apiUrl,
        success: function (response) {
            console.log(response);
        }
    };
    options.data = options.data.replace('"token":', '"token": ');
    my_ajax(options);
}

// 获取token
function get_token() {
    // 实际获取方式
    //let token = localStorage.getItem("token");
    let token = null;
    my_ajax({
        data: JSON.stringify({username: "user", password: "123456"}),
        url: "/all/user/login",
        success: function (data) {
            token = data.data.token;
        }
    });
    return token;
}

// 获取消息列表
function getMessages() {
    let messages = null;
    let options = {
        data: JSON.stringify({token: get_token(), page: 1, number: 10000}),
        url: "/user/message/selectMessageByReceiverId",
        success: function (response) {
            messages = response.data;
        }
    };
    options.data = options.data.replace('"token":', '"token": ');
    my_ajax(options);
    return messages;
}

// 设置所有消息已读
function setAllMessageIsRead() {
    let options = {
        data: JSON.stringify({token: get_token()}),
        url: "/user/message/updateMessagesStatesByReceiverId",
        success: function (response) {
            console.log(response);
        }
    };
    options.data = options.data.replace('"token":', '"token": ');
    my_ajax(options);
    $(".message-state").removeClass("icon-youjianxinxiicon").addClass("icon-yiduxiaoxi");
    $(".read-button").remove();
}

// 删除所有已读消息
function deleteAllReaded() {
    let options = {
        data: JSON.stringify({token: get_token()}),
        url: "/user/message/deleteMessagesByReceiverIdAndState",
        success: function (response) {
            console.log(response);
        }
    };
    options.data = options.data.replace('"token":', '"token": ');
    my_ajax(options);
    $(".icon-yiduxiaoxi").parent().parent().remove();
}


// 根据数据渲染界面
function setMessageList() {
    let messageList = getMessages().messages;
    let sysHTML = "";
    let personalHTML = "";
    for (let message of messageList) {
        if (message.messageType === 0)
            sysHTML += getSingleHTML(message);
        else
            personalHTML += getSingleHTML(message)
    }
    $("#system-message").html(sysHTML);
    $("#personal-message").html(personalHTML);
}

// 设置单个消息格
function getSingleHTML(message) {
    let messageState = message.messageState === 1 ? "youjianxinxiicon" : "yiduxiaoxi";
    let readButton = message.messageState === 1 ? '<button class="btn btn-primary btn-sm read-button">标为已读</button>' : "";
    let html = "";
    if (message.messageType === 0) {
        html = '<div class="card">\n' +
            '                <div class="card-header" style="font-size: 20px;text-align: center">\n' +
            '                    <span style="float: left">' + message.messageTime + '</span>\n' +
            '                    <a class="card-link" data-toggle="collapse" href="#sys-mes' + message.messageId + '">\n' +
            '                        系统提示\n' +
            '                    </a>\n' +
            '                    <button class="btn btn-warning btn-sm delete-button">删除</button>\n' + readButton +
            '                    <i class="iconfont icon-' + messageState + ' message-state"></i>\n' +
            '                </div>\n' +
            '                <div id="sys-mes' + message.messageId + '" class="collapse" data-parent="#accordion">\n' +
            '                    <div class="card-body" style="text-indent: 2em">\n' +
            '                        ' + message.messageContent + '\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>';
    } else {
        html = '<div class="card">\n' +
            '                <div class="card-header" style="font-size: 20px;text-align: center">\n' +
            '                    <span style="float: left">' + message.messageTime + '</span>\n' +
            '                    <a class="card-link" data-toggle="collapse" href="#p-mes' + message.messageId + '">\n' +
            '                        个人消息\n' +
            '                    </a>\n' +
            '                    <button class="btn btn-warning btn-sm delete-button">删除</button>\n' + readButton +
            '                    <i class="iconfont icon-' + messageState + ' message-state"></i>\n' +
            '                </div>\n' +
            '                <div id="p-mes' + message.messageId + '" class="collapse" data-parent="#accordion">\n' +
            '                    <div class="card-body" style="text-indent: 2em">\n' +
            '                        ' + message.messageContent + '\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>';
    }
    return html;
}


$(document).ready(function () {

    setMessageList();

    // 点击标题设置某条消息已读
    $(".card-header").on("click", "a", function setAlreadyRead() {
        let messageId = $(this).attr("href");
        messageId = messageId.substring(8);
        console.log(messageId);
        message_ajax("/user/message/updateMessageStateByMessageId", messageId);
        $(this).parent().children("i").removeClass("icon-youjianxinxiicon").addClass("icon-yiduxiaoxi");
    });

    // 点击按钮删除消息
    $(".delete-button").on("click", function deleteOne() {
        let messageId = $(this).parent().children("a").attr("href");
        messageId = messageId.substring(8);
        console.log(messageId);
        message_ajax("/user/message/deleteMessageByMessageId", messageId)
        $(this).parents(".card").remove();
    });

    // 点击按钮标记为已读
    $(".card-header").on("click", ".read-button", function setAlreadyRead() {
        let messageId = $(this).parent().children("a").attr("href");
        messageId = messageId.substring(8);
        console.log(messageId);
        message_ajax("/user/message/updateMessageStateByMessageId", messageId)
        $(this).parent().children("i").removeClass("icon-youjianxinxiicon").addClass("icon-yiduxiaoxi");
        $(this).hide();
    });
});